package com.ndp.fb.walle.util;

import com.ndp.fb.util.StringUtil;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by elvisxiong on 15/11/11.
 */
public class FileUploadUtils {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(FileUploadUtils.class);

    public static File multipartFile2File(MultipartFile multipartFile, String contextPath) throws IOException {
        try {
            File tmpFile = createUUIDNameFile(multipartFile.getOriginalFilename(), contextPath);
            multipartFile.transferTo(tmpFile);
            return tmpFile;
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw e;
        } catch (IllegalStateException e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
    }

    public static File bytes2File(byte[] bytes, String fileName, String contextPath) throws Exception {
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            File tmpFile = createUUIDNameFile(fileName, contextPath);
            fos = new FileOutputStream(tmpFile);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
            bos.flush();
            return tmpFile;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }  finally {
            if (null != bos) {
                try {
                    bos.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                    throw e;
                }
            }
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                    throw e;
                }
            }
        }
    }

    public static File createUUIDNameFile(String fileName, String contextPath) {
        String endType = fileName.substring(fileName.lastIndexOf("."));
        String name = UUID.randomUUID().toString() + endType;
        String sep = System.getProperty("file.separator");
        StringBuffer fileNames = new StringBuffer();
        fileNames.append(contextPath).append("upload").append(sep);
        File fileDir = new File(fileNames.toString());
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        fileNames.append(name);
        return new File(fileNames.toString());
    }

    /**
     * 获取不带扩展名的文件名
     * @param filename
     * @return
     */
    public static String getFileNameNoEx(String filename) {
        if (StringUtil.isNotEmpty(filename)) {
            int dot = filename.lastIndexOf('.');
            if ((dot >-1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename.toUpperCase();
    }

    public static String getFileNameEx(String filename) {
        if (StringUtil.isNotEmpty(filename)) {
            int dot = filename.lastIndexOf('.');
            if ((dot >-1) && (dot < (filename.length()))) {
                return filename.substring(dot+1, filename.length());
            }
        }
        return filename;
    }
}
